package com.msda.exception;

import com.alibaba.cola.dto.Response;
import com.msda.utils.Result;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(BaseException.class)
    public Result<String> handleRuntimeException(BaseException e) {
        log.error("异常信息: {}", e.getMessage());
        return Result.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "Unexpected operation occurred.");
    }

    @ExceptionHandler(Exception.class)
    public Response handleOtherException(Exception e) {
        log.warn("未知异常", e);
        return Response.buildFailure("未知异常", e.getMessage());
    }

    @RequestBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public Response handleBindException(BindException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(";"));
        log.info("参数校验不通过: {}", message);
        return Response.buildFailure("参数校验不通过", message);
    }

    @RequestBody
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Response handleDataIntegrityViolationException(DataIntegrityViolationException e) {
        Throwable rootCause = e.getRootCause();
        String message = "数据操作失败";

        if (rootCause instanceof SQLIntegrityConstraintViolationException) {
            SQLIntegrityConstraintViolationException sqlEx = (SQLIntegrityConstraintViolationException) rootCause;
            if (sqlEx.getMessage().contains("cannot be null")) {
                message = "必填字段不能为空";
            } else if (sqlEx.getMessage().contains("Duplicate entry")) {
                message = "数据已存在，请勿重复提交";
            }
        }

        log.error("数据库完整性异常: {}", e.getMessage(), e);
        return Response.buildFailure("数据校验失败", message);
    }
}
